package com.xxx.dao;

import com.xxx.pojo.Cla;
import com.xxx.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @version v1.0
 * @Description:
 * @Author zhanzhongxin
 * @Date 2021/7/29 14:17
 * @Copyright 博为峰
 */
public class ClaDaoImpl implements ClaDao {
    @Override
    public int insert(ArrayList<Cla> list) {
        String sql = "insert into cla(name,num,create_date) values (?, ?, ?)";
        try (final Connection connection = DBUtil.getConnection();
             final PreparedStatement preparedStatement = connection.prepareStatement(sql);) {
            int i = 0;
            Iterator<Cla> iterator = list.iterator();
            while (iterator.hasNext()) {
                Cla cla = iterator.next();
                preparedStatement.setString(1, cla.getName());
                preparedStatement.setInt(2, cla.getNum());
                preparedStatement.setString(3, cla.getCreateDate());
                i = preparedStatement.executeUpdate();
            }
            return i;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int delete(int claId) {
        return 0;
    }

    @Override
    public int update(Cla cla) {
        return 0;
    }

    @Override
    public ArrayList<Cla> query() {
        return null;
    }

    @Override
    public int transaction(Connection connection, ArrayList<Cla> list) {
        String sql = "insert into cla(name,num,create_date) values (?, ?, ?)";
        String querySql = "select LAST_INSERT_ID()";
        try (final PreparedStatement preparedStatement1 = connection.prepareStatement(sql);
             final PreparedStatement preparedStatement2 = connection.prepareStatement(querySql);) {
            Iterator<Cla> iterator = list.iterator();
            int claId = 0;
            while (iterator.hasNext()) {
                Cla cla = iterator.next();
                preparedStatement1.setString(1, cla.getName());
                preparedStatement1.setInt(2, cla.getNum());
                preparedStatement1.setString(3, cla.getCreateDate());
                preparedStatement1.executeUpdate();
                final ResultSet resultSet = preparedStatement2.executeQuery();
                while (resultSet.next()) {
                    claId = resultSet.getInt(1);
                }
                return claId;
            }
        } catch (SQLException throwables) {
            throw new RuntimeException("插入班级异常");
        }
        return 0;
    }
}
